//
// Created by lwj66 on 24-6-22.
//
#include "list.h"

void listInit(list* pList)
{
    pList->next = pList;
    pList->prev = pList;
}

list* creatNode(slType x)
{
    list* newNode = (list*) malloc(sizeof (list));
    if(newNode == NULL)
    {
        perror("malloc failed");
        exit(1);
    }
    newNode->x = x;
    newNode->prev = newNode->next = NULL;
    return newNode;
}

void pushFront(list* pList, slType x)
{
    list* newNode = creatNode(x);
    list* temp = pList->next;
    pList->next = newNode;
    temp->prev = newNode;
    newNode->next = temp;
    newNode->prev = pList;
}

void pushBack(list* pList, slType x)
{
    list* newNode = creatNode(x);
    list* temp = pList->prev;
    pList->prev = newNode;
    temp->next = newNode;
    newNode->next = pList;
    newNode->prev = temp;
}

void popFront(list* pList)
{
    assert(pList);
    assert(pList->prev != pList);
    pList->next = pList->next->next;
    free(pList->next->prev);
    pList->next->prev = pList;
}

void popBack(list* pList)
{
    assert(pList);
    assert(pList->prev != pList);
    pList->prev = pList->prev->prev;
    free(pList->prev->next);
    pList->prev->next = pList;
}

void insertAT(list* pos, slType x)
{
    assert(pos);
    list* newNode = creatNode(x);
    list* temp = pos->next;
    pos->next = newNode;
    temp->prev = newNode;
    newNode->next = temp;
    newNode->prev = pos;
}

void removeAT(list* pos)
{
    assert(pos);
    pos->prev->next = pos->next;
    pos->next->prev = pos->prev;
    free(pos);
}

void listPrint(list* pList)
{
    assert(pList);
    list* t = pList->next;
    while (t != pList)
    {
        printf("%d->", t->x);
        t = t->next;
    }
    printf("\n");
}

void listClear(list** ppList)
{
    list* t = (*ppList)->next;
    while (t != *ppList)
    {
        t = t->next;
        free(t->prev);
    }
}